Unique number of occurrences¶
Time: O(N); Space: O(N); easy
Given an array of integers nums, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: nums = [1,2,2,1,1,3]
Output: True
Explanation:
The value 1 has 3 occurrences, 2 has 2 and 3 has 1.
No two values have the same number of occurrences.
Example 2:
Input: nums = [1,2]
Output: False
Example 3:
Input: nums = [-3,0,1,-3,1,1,1,-3,10,0]
Output: True
Constraints:
1 <= len(nums) <= 1000
-1000 <= arr[i] <= 1000
[6]:
import collections
class Solution1(object):
"""
Time: O(N)
Space: O(N)
"""
def uniqueOccurrences(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
count = collections.Counter(nums)
lookup = set()
for v in count.values():
if v in lookup:
return False
lookup.add(v)
return True
[7]:
s = Solution1()
nums = [1,2,2,1,1,3]
assert s.uniqueOccurrences(nums) == True
nums = [1,2]
assert s.uniqueOccurrences(nums) == False
nums = [-3,0,1,-3,1,1,1,-3,10,0]
assert s.uniqueOccurrences(nums) == True
[8]:
import collections
class Solution2(object):
def uniqueOccurrences(self, nums):
"""
:type arr: List[int]
:rtype: bool
"""
count = collections.Counter(nums)
return len(count) == len(set(count.values()))
[9]:
s = Solution2()
nums = [1,2,2,1,1,3]
assert s.uniqueOccurrences(nums) == True
nums = [1,2]
assert s.uniqueOccurrences(nums) == False
nums = [-3,0,1,-3,1,1,1,-3,10,0]
assert s.uniqueOccurrences(nums) == True